$(function(){

    var provinceId,detailStr='' ;

    // 点击添加......出现添加标签的弹框
    $('.add_tag_btn').click(function(){
        $('.mask-change').show();
        $('.yao_add_tag_bounce').show();
        $('.yao_add_tag_bounce').children('div').children('input').focus();
    });

    //点击添加....出现添加分类的弹框
    $('.add_classify_btn').click(function(){
        $('.mask-change').show();
        $('.add_classify_bounce').show();
        $('.add_classify_bounce').children('div').children('input').focus();
    });

    // 获取标签列表
    function setTagList(commodityNumber,type)
    {
        $.ajax({
            type:'get',
            headers: {"Accept-CMS-Token":token},
            url:finddictlist,
            dataType:'json',
            data:{
                commodityNumber:commodityNumber,
                type:type
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    var color = data.value;
                    var len = color.length;
                    var str='';
                    for( var i=0;i<len;i++ )
                    {
                        str+='<dd class="fl project_width"><label><input type="checkbox" name="tag" value="'+color[i].id+'" class="project" description="'+color[i].name+'" checked>'+color[i].name+'</label></dd>';
                    };
                    // console.log(data)
                    $('.getTag').append(str);
                    console.log('获取标签列表接口调通!!!!')
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
                console.log('获取标签列表接口调通!!!!')
            },
            error:function(){
                console.log('获取标签列表接口请求失败')
            },
        });
    };
    // setTagList('123',4);

    //在添加标签的弹框中点击确定按钮,,,前端增加一个,,,向后台发送请求
    $('.yao_sure_add_tag').click(function(){

        var input_val = $('.tag_val').val();

        if( input_val == '' )
        {
            alert('输入内容不能为空!');
            return false;
        }
        else
        {
            $.ajax({
                type:'get',
                headers: {"Accept-CMS-Token":token},
                url:savedict,
                dataType:'json',
                data:{
                    name:input_val,
                    type:4
                },
                success:function (data){
                    if(data.resultCode == 200)
                    {
                        $('.add_tag_btn').parent('div').siblings('dl').append('<dd class="fl project_width"><label><input type="checkbox" name="tag" value="'+data.value.id+'" class="project" description="'+data.value.name+'" checked>'+data.value.name+'</label></dd>');
                        // alert('添加成功!')
                        $('.mask-change').hide()
                        $('.add_option').hide();
                        console.log('添加标签接口调通!!!!');
                    }
                    else if(data.resultCode == 515)
                    {
                        reLogin();
                    }
                },
                error:function(){
                    console.log('添加标签接口请求失败');
                },
            });

            $('.tag_val').val('');
        };

    });

    //在添加分类的弹框中点击确定按钮,,,前端增加一个...向后台发送请求
    $('.sure_add_classify').click(function(){
        if( $('.classify_name').val() == '' )
        {
            alert('输入内容不能为空!');
            return false;
        }
        else
        {
            $.ajax({
                type:'get',
                headers: {"Accept-CMS-Token":token},
                url:savedict,
                dataType:'json',
                data:{
                    name:$('.classify_name').val(),
                    type:6
                },
                success:function (data){
                    if(data.resultCode == 200)
                    {
                        $('.add_classify_btn').parent('div').siblings('dl').append('<dd class="fl project_width"><label><input type="radio" name="classify" value="'+data.value.id+'" class="project" description="'+data.value.name+'" checked>'+data.value.name+'</label></dd>');
                        // alert('添加成功!')
                        $('.mask-change').hide()
                        $('.add_option').hide();
                        console.log('添加标签接口调通!!!!');
                    }
                    else if(data.resultCode == 515)
                    {
                        reLogin();
                    }
                },
                error:function(){
                    console.log('添加标签接口请求失败');
                },
            });

            $('.classify_name').val('');
        }

    });

    //获取规格标签列表
    function setGuiGe(commodityNumber)
    {
        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:finddictlist,
            dataType:'json',
            data:{
                commodityNumber:commodityNumber,
                type:1
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    var standard = data.value;
                    var len = standard.length;
                    var str='';
                    for( var i=0;i<len;i++ )
                    {
                        str+='<option value="'+standard[i].id+'">'+standard[i].name+'</option>';
                    };
                    $('.guiGe').append(str);
                    console.log('获取标签列表接口调通!!!!')
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('获取标签列表接口请求失败')
            },
        });
    };
    setGuiGe('123');

    //产地.....要用到获取省这个接口...
    function getPlaceOfOrigin()
    {
        $.ajax({
            type:'get',
            headers: {"Accept-CMS-Token":token},
            url:provincelist,
            dataType:'json',
            data:{},
            success:function (data){
                if(data.resultCode == 200)
                {
                    var value = data.value;
                    var str = '';
                    for( var i = 0;i<value.length;i++ )
                    {
                        str+='<option value="'+value[i].id+'">'+value[i].fullName+'</option>'

                    }
                    $('.place_of_origin').append(str);
                    console.log('获取省接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('获取省接口请求失败');
            },
        });
    };
    getPlaceOfOrigin();

    //根据省查询市.......
    function getCity( provinceId )
    {
        $.ajax({
            type:'get',
            headers: {"Accept-CMS-Token":token},
            url:findcitybyprovinceid,
            dataType:'json',
            data:{
                provinceId:provinceId
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    var value = data.value;
                    var str = '';
                    for( var i = 0;i<value.length;i++ )
                    {
                        str+='<option value="'+value[i].id+'">'+value[i].fullName+'</option>'

                    };
                    $('.city').html('');
                    $('.city').append(str);
                    console.log('根据省查询市接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('根据省查询市接口请求失败');
            },
        });
    };

    // 当place_of_origin这个change时....在调用根据省查询市这个接口,,,获取这个省对应的城市.....
    $('.place_of_origin').change(function(){

        provinceId = $('.place_of_origin option:selected').val();

        getCity( provinceId );
    });

    //上传封面图片    只能上传一张图片...
    $('.upload_fengMian').change(function(){

        upLoadOnePic(1,'.upload_fengMian','input[name = coverUrl]','.wrap_fengMian');

    });

    //上传图片封装好的函数    只能上传一张图片
    function upLoadOnePic(type,Dom_input,input_hidden,wrap_form)
    {
        var option={
            type: "post",
            headers: {"Accept-CMS-Token":token},
            url: saveshopimage,
            data: {
                fileName:'fileSize',
                type:type
            },
            dataType:'json',
            async: false,
            error: function(data){
                alert("Connection error");
            },
            success: function(data){
                if(data.resultCode == 200)
                {
                    $(Dom_input).parent('label').siblings('div').children('img').attr('src',address + data.value);
                    $(Dom_input).parent('label').siblings('div').children('img').attr('height',300);
                    $(input_hidden).val(data.value);
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
                else
                {
                    // alert('接口非200,非515,非500')
                };
            }
        };
        $(wrap_form).ajaxSubmit(option);
    };

    //点击保存,,,将整个页面的信息都保存提交给后台,,,并跳转到智能硬件的页面
    $('.save_add_zhongYao').click(function(){
        // 验证表单的text,,,radio,,,和select,,,hidden,,textarea不能为空
        var text = $('.shop_info input[type = text]');
        var number = $('.shop_info input[type = number]');

        // 验证number输入框不能为空
        for(var i = 0;i<number.length;i++)
        {
            if(number.eq(i).val() == '')
            {
                $(number).eq(i).after('<span class="tips">*不能为空</span>');
                return false;
            }
            else
            {
                $(number).eq(i).siblings('span.tips').html('');
            };
        };

        // 验证text不能为空
        for(var i = 0;i<text.length;i++)
        {
            if(text.eq(i).val() == '')
            {
                $(text).eq(i).after('<span class="tips">*不能为空</span>');
                return false;
            }
            else
            {
                $(text).eq(i).siblings('span').html('');
            };
        };

        // 验证radio不能为空         getClassify...不能为空
        if( $('.shop_info input[name = classify]:checked').val() == undefined )
        {
            $('.getClassify').append('<dd class="fl project_width span_tips"><span class="tips">*不能为空</span></dd>');
            return false;
        }
        else
        {
            $('.getClassify').children('dd.span_tips').html('');
        };

        //验证select不能为空      status不能为空
        if( $('.status option:selected').val() == 0 )
        {
            $('.status').after('<span class="tips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('.status').parent('dd').children('span.tips').html('');
        };
        //验证select不能为空      place_of_origin不能为空
        if( $('.place_of_origin option:selected').val() == 0 )
        {
            $('.place_of_origin').parent('label').append('<span class="tips">*不能为空</span>');
            return false;
        }
        else
        {
            $('.place_of_origin').parent('label').children('span.tips').html('');
        };
        //验证select不能为空      city不能为空
        if( $('.city option:selected').val() == 0 )
        {
            $('.city').parent('label').append('<span class="tips">*不能为空</span>');
            return false;
        }
        else
        {
            $('.city').parent('label').children('span.tips').html('');
        };

        //验证select不能为空      guiGe不能为空
        if( $('.guiGe option:selected').val() == 0 )
        {
            $('.guiGe').after('<span class="tips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('.guiGe').parent('dd').children('span.tips').html('');
        };
        //上传图片不能为空      detailUrl不能为空
        if( $('input[name = coverUrl]').val() == '')
        {
            $('input[name = coverUrl]').parent('label').after('<span class="tips picTips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('input[name = coverUrl]').parent('label').siblings('span.picTips').html('');
        };
        // 验证textarea的内容不能为空
        // var textarea = $('.shop_info textarea');
        // for( var j=0;j<textarea.length;j++ )
        // {
        //     if( textarea.eq(j).val() == '' )
        //     {
        //         $(textarea).eq(j).after('<span class="tips textareaTips" style="margin:0 0 0 10px;">*不能为空</span>');
        //         return false;
        //     }
        //     else
        //     {
        //         $(textarea).eq(j).parent('dd').children('span.textareaTips').html('');
        //     };
        // };
        //向后台发送请求!!!
        sendAjax();
    });

    // 封装好的函数向后台传递参数,,,当发送成功以后跳转整个页面
    function sendAjax()
    {
        var lableIdStr = '';
        var lableNameStr = '';
        //获取被选中的checkbox....就是获取被选中的标签...
        for( var i=0;i<$('input[name = tag]:checked').length;i++ )
        {
            lableIdStr = lableIdStr + $('input[name = tag]:checked').eq(i).val() + ',';
            lableNameStr = lableNameStr + $('input[name = tag]:checked').eq(i).attr('description') + ',';
        };

        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:saveshopcommondity,
            dataType:'json',
            data:{
                afterSalesService:'',
                alias:$('input[name = alias]').val(),
                areaCityId:$('.city option:selected').val(),
                areaCityName:$('.city option:selected').html(),
                areaProvinceId:$('.place_of_origin option:selected').val(),
                areaProvinceName:$('.place_of_origin option:selected').html(),
                categoryId:$('input[name = classify]').val(),
                categoryName:$('input[name = classify]').attr('description'),
                colorId:'',
                colorName:'',
                company:$('input[name = company]').val(),
                coverUrl:$('input[name = coverUrl]').val(),
                detailUrl:'',
                directions:'',
                effect:$('textarea[name = effect]').val(),
                info:$('textarea[name = info]').val(),
                lableId:lableIdStr,
                lableName:lableNameStr,
                machining:$('textarea[name = machining]').val(),
                meridian:$('textarea[name = meridian]').val(),
                modelName:'',
                name:$('input[name = name]').val(),
                number:$('input[name = number]').val(),
                packingList:'',
                parameterUrl:'',
                position:$('input[name = position]').val(),
                price:$('input[name = price]').val(),
                publicCommodityHardUrl:'',
                publicCommodityMedicineUrl:'',
                shape:$('textarea[name = shape]').val(),
                sizeId:'',
                sizeName:'',
                specificationId:$('.guiGe option:selected').val(),
                specificationName:$('.guiGe option:selected').html(),
                status:$('.status option:selected').val(),
                taboo:$('textarea[name = taboo]').val(),
                taste:$('textarea[name = taste]').val(),
                totalNum:$('input[name = totalNum]').val(),
                type:2,
                useing:$('textarea[name = useing]').val()
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    alert('保存成功!');
                    window.location.href = shangpin_admin;
                    console.log('新增中药接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('新增中药接口请求失败');
            },
        });

    };

    // 点击载入...将后台的信息载入到前端的页面当中
    $('.yao_load_info').click(function(){
        var name = $('input[name = name]').val(),
            number = $('input[name = number]').val();

        if( name == '' && number == '' )
        {
            alert('亲,请输入编号或者名称!');
        }
        else
        {
            // 获取到值以后向后台发送请求
            $.ajax({
                type:'get',
                headers: {"Accept-CMS-Token":token},
                url:findbynameornumber,
                dataType:'json',
                data:{
                    name:name,
                    number:number
                },
                success:successLoadInfo,
                error:function(){
                    console.log('根据名称查找接口请求失败');
                },
            });
        };

    });

    // 载入中的ajax请求成功的时候执行这个函数.......
    function successLoadInfo(data)
    {
        if(data.resultCode == 200)
        {
            var value = data.value;
            if(value.length > 0)
            {
                // 将后台返回来的数据取其中一条...回显到页面当中...
                $('input[name = number]').val( value[0].number );
                $('input[name = name]').val( value[0].name );
                $('input[name = price]').val( value[0].price );
                $('input[name = totalNum]').val( value[0].totalNum );
                $('input[name = modelName]').val( value[0].modelName );
                $('input[name = company]').val( value[0].company );
                $('input[name = alias]').val( value[0].alias );
                $('input[name = position]').val( value[0].position );

                // 标签回显...载入的时候...先清空...然后重新载入...
                clearTag();
                var lableIdStr = value[0].lableId.split(',');
                var lableNameStr = value[0].lableName.split(',');;
                for( var a=0;a<lableIdStr.length-1;a++ )
                {
                    $('.getTag').append('<dd class="fl project_width"><label><input type="checkbox" name="tag" value="' + lableIdStr[a] + '" class="project" description="' + lableNameStr[a] + '" checked>' + lableNameStr[a] + '</label></dd>');
                };

                // 状态回显
                if( value[0].status == 1 )
                {
                    $('.status option').eq(1).attr( 'selected','selected' );
                }
                else
                {
                    $('.status option').eq(2).attr( 'selected','selected' );
                };
                // 产地----省回显
                for( var i=0;i<$('.place_of_origin option').length;i++ )
                {
                    if( $('.place_of_origin option').eq(i).val() == value[0].areaProvinceId )
                    {
                        $('.place_of_origin option').eq(i).attr( 'selected','selected' );
                        break;
                    };
                };
                getCity( value[0].areaProvinceId );
                // 产地-----市回显
                for( var j=0;j<$('.city option').length;j++ )
                {
                    if( $('.city option').eq(j).val() == value[0].areaCityId )
                    {
                        $('.city option').eq(j).attr( 'selected','selected' );
                        break;
                    };
                };
                // 规格回显
                for( var q=0;q<$('.guiGe option').length;q++ )
                {
                    if( $('.guiGe option').eq(q).val() == value[0].specificationId )
                    {
                        $('.guiGe option').eq(q).attr( 'selected','selected' );
                        break;
                    }
                };
                $('.wrap_datail div div img').attr( 'src',address + value[0].detailUrl );
                $('.wrap_datail div div img').attr( 'height',300 );
                $('input[name = detailUrl]').val( value[0].detailUrl );
                $('textarea[name = info]').val( value[0].info );
                $('textarea[name = shape]').val( value[0].shape );
                $('textarea[name = machining]').val( value[0].machining );
                $('textarea[name = taste]').val( value[0].taste );
                $('textarea[name = meridian]').val( value[0].meridian );
                $('textarea[name = effect]').val( value[0].effect );
                $('textarea[name = packingList]').val( value[0].packingList );
                $('textarea[name = useing]').val( value[0].useing );
                $('textarea[name = taboo]').val( value[0].taboo );

            };
            // console.log(data)
            console.log('根据名称查找接口调通!!!!');
        }
        else if(data.resultCode == 500)
        {
            alert('亲,商品原来没有!请重新输入......');
        }
        else if(data.resultCode == 515)
        {
            reLogin();
        }
    };
    //载入商品信息的标签...先清空...然后重新加载..
    function clearTag()
    {
        $('.getTag').html('');
        $('.getTag').append('<dt class="fl">标签</dt>');
    };


});
